'use strict'
import React from 'react'
import style from '../css.css'

class HomePage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      name: '',
      isToast: false
    }
    this.goPlay = this.goPlay.bind(this)
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange (e) {
    const name = e.target.value
    this.setState({ name })
  }
  goPlay () {
    const { name, isToast } = this.state
    if (isToast) { return false }
    else {
      if (name.length === 0) {
        this.setState({ isToast: true })
      }
      else {
        const fetchURL = `https://m2.qiushibaike.com/myfoolday?name=${name}&c=1`
        fetch(fetchURL, { method: 'get' })
          .then(res => res.json())
          .then(res => {
            const { sign } = res
            if (!sign) {
              window.location.href = `${window.location}?page=1&name=${this.state.name}`
            }
            else {
              this.setState({ isToast: true })
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    }
  }
  _toast () {
    const { isToast } = this.state
    if (isToast) {
      return (
        <div className={style.toast}>请输入合规的昵称哦~</div>
      )
    }
    setTimeout(() => {
      this.setState({ isToast: false })
    }, 3000)
  }
  render () {
    return (
      <div className={style.homePage}>
        <div className={style.bgImg}></div>
        <input className={style.inputBtn} type='text' maxLength='5' placeholder="请输入小伙伴的昵称（1-5个字符）" onChange={this.handleChange} />
        <div className={style.playRegion}>
          <div className={style.leftIcon}></div>
          <div className={style.playBtn} onClick={this.goPlay}>开始玩耍</div>
          <div className={style.rightIcon}></div>
        </div>
        <div className={style.activeState}></div>
        {this._toast()}
      </div>
    )
  }
}

export default HomePage
